<template>
	<view class="ops-create">
		<up-cell-group class="setting-form" :border="false">
			<up-cell isLink :title="$t('ops.create.cell-1')" @click="showSiteOptions = true">
				<template #value>
					<up-input readonly :modelValue="formData.siteName" class="readonly" border="none" inputAlign="right"
						:placeholder="$t('ops.create.cell-1.placeholder')"></up-input>
				</template>
			</up-cell>
			<up-cell :title="$t('ops.create.cell-2')">
				<template #value>
					<up-input v-model="formData.repairman" border="none" inputAlign="right"
						:placeholder="$t('ops.create.cell-2.placeholder')"></up-input>
				</template>
			</up-cell>
			<up-cell :title="$t('ops.create.cell-3')">
				<template #value>
					<up-input v-model="formData.phone" border="none" type="tel" inputAlign="right"
						:placeholder="$t('ops.create.cell-3.placeholder')"></up-input>
				</template>
			</up-cell>
			<up-cell :title="$t('ops.create.cell-4')">
				<template #value>
					<up-input v-model="formData.email" border="none" type="email" inputAlign="right"
						:placeholder="$t('ops.create.cell-4.placeholder')"></up-input>
				</template>
			</up-cell>
			<up-cell :title="$t('ops.create.cell-5')">
				<template #label>
					<up-textarea v-model="formData.content" class="textarea-input" count :maxlength="500" border="none"
						:placeholder="$t('ops.create.cell-5.placeholder')"></up-textarea>
				</template>
			</up-cell>
			<up-cell :title="$t('ops.create.cell-6')">
				<template #label>
					<up-upload class="upload-input" :fileList="files" sizeType="original" width="180rpx" height="180rpx"
						:max-count="MAX_COUNT" multiple upload-icon="plus" upload-icon-color="#ddd"
						@afterRead="handleSelect" @delete="handleDlete" @error="handleError"></up-upload>
				</template>
			</up-cell>
		</up-cell-group>
		<up-picker :show="showSiteOptions" :title="$t('ops.create.cell-7')" closeOnClickOverlay :columns="siteList"
			:confirm-text="$t('time.confirm')" :cancel-text="$t('time.cancel')" keyName="siteName"
			@close="showSiteOptions = false" @confirm="handleSiteChange">
			<!-- <template #toolbar-right>
				<up-icon class="toolbar-right-close" name="close" @tap="showSiteOptions = false"></up-icon>
			</template> -->
		</up-picker>
		<fixed-footer>
			<up-button type="primary" size="large" shape="circle"
				@tap="handleSubmit">{{ $t("ops.create.submit.btn") }}</up-button>
		</fixed-footer>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from "vue";
	import {
		addOperate,
		selectSiteNameList
	} from "../../apis/components/operate";
	import {
		useI18n
	} from "vue-i18n";
	import {
		uploadFile
	} from "../../apis/components/file";

	const {
		t
	} = useI18n();

	const showSiteOptions = ref(false);
	const MAX_COUNT = 9;
	const formData = reactive({
		content: "",
		email: "",
		files: [],
		phone: "",
		repairman: "",
		siteId: "",
		siteName: "",
	});
	const siteList = ref([]);

	const files = ref([]);

	const handleDlete = (event) => {
		files.value.splice(event.index, 1);
	};

	const handleSelect = async ({
		file
	}) => {
		let lists = [].concat(file);
		let fileListLen = files.value.length;
		lists.map((item) => {
			files.value.push({
				...item,
				status: "uploading",
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFile(lists[i].url);
			let item = files.value[fileListLen];
			files.value.splice(fileListLen, 1, {
				...item,
				status: "success",
				url: result,
			});
			fileListLen++;
		}
		if (beRequest.value) {
			beRequest.value = false;
			handleSubmit();
		}
	};

	const handleSiteChange = ({
		value
	}) => {
		const [site] = value || [];
		formData.siteId = site.siteId;
		formData.siteName = site.siteName;
		showSiteOptions.value = false;
	};

	const loadData = async () => {
		const sites = await selectSiteNameList();
		siteList.value = [sites];
	};

	const handleError = ({
		errMsg,
		code
	}) => {
		if ([2, 11, 12].includes(Number(code)) && !errMsg.includes(
				'User cancelled')) {
			uni.showModal({
				title: t("common.permissionPrompts"),
				content: `${t("common.pleaseGrant")}${code === 12 ? t("common.photoAlbum"): t("common.camera")}${t("common.permissionToUseTheFeature")}`,
				confirmText: t("common.goToSettings"),
				cancelText: t("common.cancel"),
				success: (res) => {
					if (res.confirm) {
						uni.openAppAuthorizeSetting();
					}
				},
			});
		}
	}

	const handleSubmit = async () => {
		try {
			let errorMessage = "";
			if (!formData.siteId || !formData.siteName) {
				errorMessage = t("ops.create.warn-1");
			} else if (!formData.repairman) {
				errorMessage = t("ops.create.warn-2");
			} else if (formData.phone && !/^\d+$/.test(formData.phone)) {
				errorMessage = t("ops.create.warn-3");
			} else if (formData.email && !uni.$u.test.email(formData.email)) {
				errorMessage = t("ops.create.warn-4");
			} else if (!formData.content) {
				errorMessage = t("ops.create.warn-5");
			}
			if (errorMessage) {
				uni.$u.toast(errorMessage);
				return;
			}
			formData.picture = files.value.map((item) => item.url).join(";");
			await addOperate(formData);
			uni.$u.toast(t("ops.create.successful"));
			uni.navigateBack();
		} catch (err) {
			uni.$u.toast(typeof err === "string" ? err : err.message);
		}
	};

	loadData();
</script>

<style lang="scss" scoped>
	.ops-create {
		padding: 24rpx 32rpx;

		.readonly {
			pointer-events: none;
		}

		.textarea-input {
			margin-top: 40rpx;
			background-color: #222d49;
			border-radius: 16rpx;

			& ::v-deep .u-textarea__field {
				color: #ddd;
			}

			& ::v-deep .u-textarea__count {
				background-color: transparent !important;
			}
		}

		.upload-input {
			margin-top: 40rpx;
		}

		& ::v-deep .u-upload {
			.u-upload__button {
				background-color: #222d49;
				border-radius: 12rpx;
				margin: 0 23rpx 23rpx 0;
			}

			.u-upload__wrap__preview {
				margin: 0 20rpx 20rpx 0;
			}
		}
	}
</style>